<template>
  <div>
    <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="ruleForm.name" autocomplete="off" />
      </el-form-item>

      <el-form-item label="部门编号" prop="code">
        <el-input v-model="ruleForm.code" autocomplete="off" />
      </el-form-item>

      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="ruleForm.manager" placeholder="请选择部门负责人" style="width:100%">
          <el-option
            v-for="item in Employees"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />

        </el-select>
      </el-form-item>

      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="ruleForm.introduce" type="textarea" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployees } from '@/api/employees'
import { addDartments, getupDartments, updatDartments } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },

  data() {
    const validCode = (rule, value, callback) => {
      let existCodeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (existCodeList.includes(value)) {
        callback(new Error('部门编号' + value + '已存在'))
      } else {
        callback()
      }
    }
    const validName = (rule, value, callback) => {
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      if (this.isEdit) {
        const curDepartments = this.originList.find(item => item.id === this.id)
        const pid = curDepartments.pid
        const brothers = this.originList.filter(item => item.pid === pid)
        existNameList = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }
      if (existNameList.includes(value)) {
        callback(new Error('部门名称' + value + '已存在'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      Employees: [],
      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: ['blur'] },
          { min: 2, max: 50, message: '请输入长度是1~15的字符', trigger: ['blur'] },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编号', trigger: ['blur'] },
          { min: 2, max: 50, message: '请输入长度是1~15的字符', trigger: ['blur'] },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: ['blur', 'change'] }
        ],
        introduce: [{ required: true, message: '请输入部门介绍', trigger: ['blur'] },
          { min: 2, max: 50, message: '请输入长度是1~300的字符', trigger: ['blur'] }]
      }
    }
  },
  watch: {
    'id': function(newVal, oldVal) {
      // 重发请求获取详情
      if (this.isEdit) {
        this.loadDepartmentsDetail()
      } else {
        this.$refs.ruleForm.resetFields()
      }
    }
  },
  mounted() {

  },
  created() {
    this.loadEmployees()
    if (this.isEdit) {
      this.loadDepartmentsDetail()
    } else {
      this.$refs.ruleForm.resetFields()
    }
  },

  methods: {
    resetForms() {
      this.$refs.ruleForm.resetFields()
    },
    async submitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    async doAdd() {
      try {
        const res = await addDartments({ ...this.ruleForm, pid: this.id })
        if (res.code !== 10000) {
          this.$message.success(res.message)
        }
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    resetForm(formName) {
      this.$emit('close')
    },
    // 渲染员工列表
    async loadEmployees() {
      try {
        const res = await getEmployees()
        this.Employees = res.data
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
      this.isEdit ? this.doEdit() : this.doAdd()
    },
    // 修改数据
    async  doEdit() {
      try {
        const res = await updatDartments({ ...this.ruleForm, id: this.id })
        if (res.code !== 10000) {
          this.$message.success(res.manager)
        }
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 数据回填
    async loadDepartmentsDetail() {
      try {
        const res = await getupDartments(this.id)
        this.ruleForm = res.data
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="sass" scoped>

</style>
